package logic

import (
	"activity/activityRpc/activityRpc"
	"activity/activityRpc/internal/svc"
	"activity/models/cache"
	"activity/models/mysql"
	"activity/pkg"
	"context"
	"fmt"

	"github.com/zeromicro/go-zero/core/logx"
)

type RegisterLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
	return &RegisterLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RegisterLogic) Register(in *activityRpc.RegisterRequest) (*activityRpc.RegisterResponse, error) {
	// todo: add your logic here and delete this line

	findUser := mysql.User{}
	mysql.DB.Where("tel=?", in.Tel).Find(&findUser)

	if findUser.ID != 0 {
		return nil, fmt.Errorf("当前手机号已注册，请前去登录")
	}

	sms, err := cache.Rdb.Get(l.ctx, "sendSms"+in.Tel).Result()
	if err != nil {
		return nil, err
	}
	if sms != in.SmsCode {
		return nil, fmt.Errorf("短信验证码错误")
	}

	user := mysql.User{
		Tel:      in.Tel,
		Password: pkg.Md5(in.Password),
	}

	mysql.DB.Create(&user)

	return &activityRpc.RegisterResponse{
		Id: int64(user.ID),
	}, nil
}
